package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 1: 查出所有的列表
     * 2: 通过列表中的parent_cid来过滤, 过滤出来的都是一级分类
     * 3: 然后通过过滤的一级分类进行映射, 映射出所有子分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityList = categoryDao.selectList(null);
        return categoryEntityList.stream().filter(p -> p.getParentCid() == 0).map(p -> {
            p.setChildTree(getChildTree(p, categoryEntityList));
            return p;
        }).collect(Collectors.toList());
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        categoryDao.deleteBatchIds(asList);
    }

    /**
     * 查找所有的子分类
     *
     * @param categoryEntity
     * @param categoryEntityList
     * @return
     */
    private List<CategoryEntity> getChildTree(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntityList) {
        /**
         * filter:表明筛选出所有的子分类(二级)
         *
         * 若filter过滤时为null, 则map后面的不执行,直接终止了stream任务;
         */
        return categoryEntityList.stream().filter(p -> p.getParentCid().equals(categoryEntity.getCatId()))
                .map(p -> {
                    p.setChildTree(getChildTree(p, categoryEntityList));
                    return p;
                })
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        System.out.println(list);
        list.add(1);
        List<Integer> collect = list.stream().map(p -> {
            System.out.println(p);
            return p;
        }).collect(Collectors.toList());
        System.out.println(collect);
    }

}